package com.olda.play.auth.security.userdetails.web;

import com.olda.play.constant.Constant;
import com.olda.play.constant.PasswordEncoderTypeEnum;
import com.olda.play.system.dto.SysUserDto;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;


/**
 * 系统管理用户认证信息
 */
@Data
public class SysUserDetails implements UserDetails {

    /**
     * 扩展字段：用户ID
     */
    private Long userId;

    /**
     * 扩展字段：认证身份标识，枚举值如下：
     *
     */
    private String authenticationIdentity;

    /**
     * 扩展字段：部门ID
     */
    private Long deptId;

    /**
     * 默认字段
     */
    private String username;
    private String password;
    private Boolean enabled;


    private Collection<SimpleGrantedAuthority> authorities;


    /**
     * 系统-web端用户-转UserDetails
     */
    public SysUserDetails(SysUserDto sysUserDto) {
        this.setUserId(sysUserDto.getId());
        this.setUsername(sysUserDto.getUserName());
        this.setDeptId(sysUserDto.getDeptId());
        this.setPassword(PasswordEncoderTypeEnum.BCRYPT.getPrefix() + sysUserDto.getPassword());
        this.setEnabled(Constant.IS_YES .equals(sysUserDto.getStatus()));
       /*if(sysUserDto.getRoleId()!=null){
           authorities = new ArrayList<>();
           authorities.add(new SimpleGrantedAuthority(sysUserDto.getRoleCode()));
       }*/
        if(sysUserDto.getRoleId()!=null){
            authorities = new ArrayList<>();
            authorities.add(new SimpleGrantedAuthority(sysUserDto.getRoleId().toString()));
        }
    }



    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.authorities;
    }

    @Override
    public String getPassword() {
        return this.password;
    }

    @Override
    public String getUsername() {
        return this.username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /**
     * 账户是否可用
     * @return
     */
    @Override
    public boolean isEnabled() {
        return this.enabled;
    }
}
